//
//  AddAdressController.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/29.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD

class AddAdressController: BaseViewController {
    
    var areaDataModels : [ProvinceModel]?
    
    
    var block : (() -> ())?


    
    var dataModel : FillAddressInfoModel = FillAddressInfoModel()
    
    lazy var animedDelegate : PopoverAnimDelegate = {
        
        let tempDelegate = PopoverAnimDelegate(tempBlock: {[weak self] (isPresented) in
            
            QL1(isPresented)
        })
        
        return tempDelegate
        
    }()

    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadCitysInfo()
        
        navigationItem.title = "新建收货地址"
        
        plainTableView.rowHeight = UITableViewAutomaticDimension
        
        plainTableView.estimatedRowHeight = 100
        
        plainTableView.tableFooterView = UIView()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: .plain, target: self, action: #selector(saveAdressInfo))


        plainTableView.register(UINib(nibName: StringFromClass(classType: LinkmanNameCell.self), bundle: nil), forCellReuseIdentifier: LinkmanNameCell.identifer())

        plainTableView.register(UINib(nibName: StringFromClass(classType: ProvincialsSeletCell.self), bundle: nil), forCellReuseIdentifier: ProvincialsSeletCell.identifer())

        plainTableView.register(UINib(nibName: StringFromClass(classType: DetailAressCell.self), bundle: nil), forCellReuseIdentifier: DetailAressCell.identifer())


    }
    
    func saveAdressInfo(){
        view.endEditing(true)
//        var trueName : String?
//        var phoneNumber : String?
//        var areaInfo : String?
//        var detailAderss : String?
//        
//        var province_name : String?
//        var province_id  : String?
//        
//        var city_id  : String?
//        var city_name  : String?
//        
//        var district_id  : String?
//        var district_name  : String?
        
        if dataModel.trueName == nil {
            
            alert(str: "请填写收货人姓名")
            return
        }else{
            if dataModel.trueName!.characters.count < 1 {
                
                alert(str: "请填写收货人姓名")
                
            }
        }
        
        if dataModel.phoneNumber == nil {
            alert(str: "请填写手机号")
            return
        }
        
        if isPhoneNumber() == false{
            alert(str: "手机号格式不正确")
            return
            
        }
        
        
        if dataModel.areaInfo == nil {
            alert(str: "请选择所在地区")
            return
        }
        
        
        if dataModel.detailAderss == nil {
            alert(str: "请填写详细地址")
            return
        }else{
            if dataModel.detailAderss!.characters.count < 1 {
                
                alert(str: "请填写详细地址")
                
                return
                
            }
        }
        
        
        QL1(dataModel)
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["true_name"] = "\(dataModel.trueName!)" as AnyObject
        parmeter["mob_phone"] = "\(dataModel.phoneNumber!)" as AnyObject
        parmeter["area_info"] = "\(dataModel.areaInfo!)" as AnyObject
        parmeter["is_default"] = "0" as AnyObject
        parmeter["address"] = "\(dataModel.detailAderss!)" as AnyObject
        parmeter["province_id"] = "\(dataModel.province_id!)" as AnyObject
        parmeter["city_id"] = "\(dataModel.city_id!)" as AnyObject
        
        if dataModel.district_id != nil {
            parmeter["area_id"] = "\(dataModel.district_id!)" as AnyObject

        }
        
        
        NetworkTools.shared.sendRequest(method: .POST_METHOD, pathStr: "mobile/index.php?c=member_address&a=address_add", parameters: parmeter) { [weak self] (responseObject, error) in
            
            
            if error  == nil{
                
                SVProgressHUD.showSuccess(withStatus: "添加成功")
                
                if self?.block != nil{
                    
                    self?.block!()
                    
                }
                
                
                self?.perform(#selector(self?.sussesPop), with: nil, afterDelay: 0.5)
                
                
                
            }else{
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
        }
        
        
        
        
        
    }
    
    
    
    func sussesPop() {
        SVProgressHUD.dismiss()
        
        navigationController?.popViewController(animated: true)
        
    }
    
    

    
    
    func isPhoneNumber() -> Bool {
        
        if dataModel.phoneNumber!.characters.count < 1 {
            return false
        }
        
        //电话号码
        let pattern = "[1][0-9]{10}"
        
        //caseInsensitive  忽略大小写  最常用
        //dotMatchesLineSeparators 允许 . 匹配任意字符，包括回车换行
        let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
        
        
        //根据规则匹配指定字符串中第一个符合规则的字符串，并且返回一个NSTextCheckingResult
        let res = regex.firstMatch(in: dataModel.phoneNumber!, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range:  NSRange(location: 0, length: dataModel.phoneNumber!.characters.count))
        
        
        if res?.range != nil {
            return true
            
        }else{
            
            return false
            
        }
        
        
        
    }
    
    
    func alert(str : String) {
        
        let tempVC = UIAlertController(title: nil, message: str, preferredStyle: .alert)
        
        let action1 = UIAlertAction(title: "确定", style: .destructive) { (action) in
            
        }
        
        
        
        let action2 = UIAlertAction(title: "取消", style: .default) { (action) in
            
            
        }
        
        tempVC.addAction(action2)
        tempVC.addAction(action1)
        
        present(tempVC, animated: true, completion: nil)
        
        
    }
    

    
    
    func loadCitysInfo(){
        
    NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=index&a=get_area_list", parameters: nil) {[weak self] (responseObject, error) in
    
         if error == nil{
        
    
           self!.areaDataModels = [ProvinceModel]()
        
    
           for dic in responseObject!["datas"]!["area_list"] as! [[String : AnyObject]]{
    
    
           self!.areaDataModels!.append(ProvinceModel(dic: dic))
    
    
                    }
            
            
            for tempProvinceModel in self!.areaDataModels! {
                
                for tiModel in tempProvinceModel.citys {
                    tiModel.province_id = tempProvinceModel.province_id
                    
                    tiModel.province_name = tempProvinceModel.province_name
                    
                    for disModel in tiModel.districts {
                        
                        disModel.province_name = tiModel.province_name
                        
                        disModel.province_id = tiModel.province_id
                        
                        disModel.city_id = tiModel.city_id
                        
                        disModel.city_name = tiModel.city_name
                        
                        
                    }
                    
                    
                }
                
            }

       
    
    
            }
        
    }
    
}
    




    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}


extension AddAdressController:LinkmanNameCellDelegate{
    
    
    func selectContactBtnDidTap() {
        view.endEditing(true)
        
        
        let temp = PhoneNumberListVC()
        
        temp.block = { (name,phoneNumber) -> () in
            
            self.dataModel.trueName = name
            
            self.dataModel.phoneNumber = phoneNumber
            
            self.plainTableView.reloadData()
            
            
        }
        
        
        present(BaseNavController(rootViewController: temp), animated: true) {
            
            
        }


    }



    
}


extension AddAdressController{
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        
        return 1
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        
        return 3
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var tableCell : UITableViewCell? = nil
        
        if indexPath.row == 0 {
            
            let tempCell : LinkmanNameCell =  tableView.dequeueReusableCell(withIdentifier: LinkmanNameCell.identifer()) as! LinkmanNameCell
            
            tempCell.model = dataModel
            
            tempCell.delegate = self
            
            tableCell = tempCell

        } else if indexPath.row == 1 {
            
            let tempCell : ProvincialsSeletCell =  tableView.dequeueReusableCell(withIdentifier: ProvincialsSeletCell.identifer()) as! ProvincialsSeletCell
            tempCell.model = dataModel

            tableCell = tempCell
 
        }else{
        
            
            let tempCell : DetailAressCell =  tableView.dequeueReusableCell(withIdentifier: DetailAressCell.identifer()) as! DetailAressCell
            
            tempCell.model = dataModel

            tempCell.tableView = plainTableView
            
            tableCell = tempCell

        
        }

     
        
        return tableCell!
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        view.endEditing(true)
        if indexPath.row == 1 {
            QL1("选择地区")
            if areaDataModels != nil {
                
                let temp = PopoverAdressController()
                
                temp.dataModels = areaDataModels
                
                temp.block = { (model,model2) -> () in
                    
                    if model != nil {
                        
                        self.dataModel.province_name = model!.province_name
                        self.dataModel.province_id = model!.province_id
                        self.dataModel.city_name = model!.city_name
                        self.dataModel.city_id = model!.city_id
                        self.dataModel.district_name = model!.district_name
                        self.dataModel.district_id = model!.district_id
                        
                         self.dataModel.areaInfo = "\(model!.province_name)\(model!.city_name)\(model!.district_name)"
                        

                    } else {
                        
                        self.dataModel.province_name = model2!.province_name
                        self.dataModel.province_id = model2!.province_id
                        self.dataModel.city_name = model2!.city_name
                        self.dataModel.city_id = model2!.city_id
                        self.dataModel.district_name = nil
                        self.dataModel.district_id = nil
           
                        
                        self.dataModel.areaInfo = "\(model2!.province_name)\(model2!.city_name)"
                        

                    }
                    
                    self.plainTableView.reloadData()
                
                }
                
                
                temp.transitioningDelegate = animedDelegate
                temp.modalPresentationStyle = .custom
                
                present(temp, animated: true, completion: nil)

                
            }
            
        }
    }
    
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        view.endEditing(true)
        
    }
    
       
    
}




